"""
主窗口 - 单窗口百万级trace事件可视化
"""
from typing import Optional
from PySide6.QtWidgets import (
    QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QTableView, QPushButton, QLabel, QSplitter,
    QGroupBox, QSpinBox, QCheckBox
)
from PySide6.QtCore import Qt, QTimer, Slot
from PySide6.QtGui import QFont

try:
    # 相对导入（作为包运行时）
    from .data_model import MetricsModel, DataAggregator
    from .sampler import RealTimeSamplingController
    from .table_model import VirtualTableModel, StatisticsModel
    from .config import CONFIG
except ImportError:
    # 绝对导入（直接运行时）
    from data_model import MetricsModel, DataAggregator
    from sampler import RealTimeSamplingController
    from table_model import VirtualTableModel, StatisticsModel
    from config import CONFIG


class MIMainWindow(QMainWindow):
    """MI测试工具主窗口"""
    
    def __init__(self, parent: Optional[QWidget] = None):
        super().__init__(parent)
        
        # 数据层
        self.metrics_model = MetricsModel()
        self.data_aggregator = DataAggregator()
        
        # 采样控制器
        self.sampling_controller = RealTimeSamplingController(self.metrics_model)
        
        # 表格模型
        self.trace_model = VirtualTableModel(self.metrics_model)
        self.stats_model = StatisticsModel(self.metrics_model)
        
        # 定时器
        self.refresh_timer = QTimer(self)
        self.refresh_timer.timeout.connect(self.on_refresh_timer)
        
        self.init_ui()
        self.setup_connections()
    
    def init_ui(self) -> None:
        """初始化UI"""
        self.setWindowTitle('MI - 新一代测试工具 v1.0')
        self.setGeometry(100, 100, 1400, 900)
        
        # 中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        
        # 顶部控制栏
        control_layout = self.create_control_panel()
        main_layout.addLayout(control_layout)
        
        # 分割器：trace表格 + 统计表格
        splitter = QSplitter(Qt.Orientation.Horizontal)
        
        # Trace事件表格
        trace_group = self.create_trace_view()
        splitter.addWidget(trace_group)
        
        # 统计信息表格
        stats_group = self.create_statistics_view()
        splitter.addWidget(stats_group)
        
        splitter.setSizes([900, 500])
        main_layout.addWidget(splitter)
        
        # 状态栏
        self.statusBar().showMessage('就绪 - 等待启动采样')
    
    def create_control_panel(self) -> QHBoxLayout:
        """创建控制面板"""
        layout = QHBoxLayout()
        
        # 采样控制
        self.btn_start = QPushButton('启动采样')
        self.btn_start.clicked.connect(self.on_start_sampling)
        layout.addWidget(self.btn_start)
        
        self.btn_stop = QPushButton('停止采样')
        self.btn_stop.clicked.connect(self.on_stop_sampling)
        self.btn_stop.setEnabled(False)
        layout.addWidget(self.btn_stop)
        
        self.btn_clear = QPushButton('清空数据')
        self.btn_clear.clicked.connect(self.on_clear_data)
        layout.addWidget(self.btn_clear)
        
        # 采样频率
        layout.addWidget(QLabel('采样频率(Hz):'))
        self.spin_rate = QSpinBox()
        self.spin_rate.setRange(1, 10000)
        self.spin_rate.setValue(CONFIG.sampling.sample_rate)
        self.spin_rate.valueChanged.connect(self.on_rate_changed)
        layout.addWidget(self.spin_rate)
        
        # C++引擎开关
        self.chk_cpp = QCheckBox('启用C++引擎')
        self.chk_cpp.setChecked(CONFIG.use_cpp_engine)
        layout.addWidget(self.chk_cpp)
        
        layout.addStretch()
        
        # 统计信息
        self.lbl_event_count = QLabel('事件数: 0')
        font = QFont()
        font.setBold(True)
        self.lbl_event_count.setFont(font)
        layout.addWidget(self.lbl_event_count)
        
        return layout
    
    def create_trace_view(self) -> QGroupBox:
        """创建trace事件视图"""
        group = QGroupBox('Trace 事件流 (百万级流畅体验)')
        layout = QVBoxLayout(group)
        
        # 表格视图
        self.trace_table = QTableView()
        self.trace_table.setModel(self.trace_model)
        self.trace_table.setAlternatingRowColors(True)
        self.trace_table.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
        
        # 性能优化
        self.trace_table.setVerticalScrollMode(QTableView.ScrollMode.ScrollPerPixel)
        self.trace_table.setHorizontalScrollMode(QTableView.ScrollMode.ScrollPerPixel)
        
        # 调整列宽
        header = self.trace_table.horizontalHeader()
        header.setStretchLastSection(True)
        
        layout.addWidget(self.trace_table)
        
        return group
    
    def create_statistics_view(self) -> QGroupBox:
        """创建统计信息视图"""
        group = QGroupBox('实时统计指标')
        layout = QVBoxLayout(group)
        
        # 统计表格
        self.stats_table = QTableView()
        self.stats_table.setModel(self.stats_model)
        self.stats_table.setAlternatingRowColors(True)
        
        # 调整列宽
        header = self.stats_table.horizontalHeader()
        header.setStretchLastSection(True)
        
        layout.addWidget(self.stats_table)
        
        return group
    
    def setup_connections(self) -> None:
        """设置信号连接"""
        self.trace_model.data_updated.connect(self.on_data_updated)
    
    @Slot()
    def on_start_sampling(self) -> None:
        """启动采样"""
        self.sampling_controller.start()
        self.btn_start.setEnabled(False)
        self.btn_stop.setEnabled(True)
        
        # 启动定时刷新
        self.refresh_timer.start(CONFIG.visualization.refresh_interval)
        
        self.statusBar().showMessage('采样中...')
    
    @Slot()
    def on_stop_sampling(self) -> None:
        """停止采样"""
        self.sampling_controller.stop()
        self.refresh_timer.stop()
        
        self.btn_start.setEnabled(True)
        self.btn_stop.setEnabled(False)
        
        self.statusBar().showMessage('已停止采样')
    
    @Slot()
    def on_clear_data(self) -> None:
        """清空数据"""
        self.metrics_model.clear()
        self.trace_model.refresh()
        self.stats_model.refresh()
        self.lbl_event_count.setText('事件数: 0')
        self.statusBar().showMessage('数据已清空')
    
    @Slot(int)
    def on_rate_changed(self, value: int) -> None:
        """采样频率变化"""
        self.sampling_controller.sampler.set_sample_rate(value)
        CONFIG.sampling.sample_rate = value
    
    @Slot()
    def on_refresh_timer(self) -> None:
        """定时刷新"""
        # 增量更新表格
        self.trace_model.refresh()
        self.stats_model.refresh()
        
        # 更新统计
        event_count = self.metrics_model.events.size
        self.lbl_event_count.setText(f'事件数: {event_count:,}')
        
        # 自动滚动到底部（最新数据）
        if event_count > 0:
            last_row = event_count - 1
            last_index = self.trace_model.index(last_row, 0)
            self.trace_table.scrollTo(last_index)
    
    @Slot()
    def on_data_updated(self) -> None:
        """数据更新回调"""
        pass
    
    def closeEvent(self, event) -> None:  # type: ignore
        """关闭事件"""
        self.sampling_controller.stop()
        self.refresh_timer.stop()
        super().closeEvent(event)
